package ru.hh.team02.chat.utils;

import java.util.LinkedList;
import java.util.List;

public class SimpleBlockingQueue<T> implements BatchBlockingQueue<T> {

    private final List<T> queue = new LinkedList<T>();

    /* (non-Javadoc)
     * @see ru.hh.team02.chat.server.SendMessage.sendingBlockingQueue.BlockingQueue#get()
     */
    @Override
    public T get() throws InterruptedException {
        synchronized (queue) {
            while (queue.isEmpty()) {
                queue.wait();
            }
            return queue.remove(0);
        }
    }

    /* (non-Javadoc)
     * @see ru.hh.team02.chat.server.SendMessage.sendingBlockingQueue.BlockingQueue#add(T)
     */
    @Override
    public void add(T obj) {
        synchronized (queue) {
            queue.add(obj);
            queue.notify(); // notify one thread blocked in the wait section of get
                            // method.
        }
    }

    /* (non-Javadoc)
     * @see ru.hh.team02.chat.server.SendMessage.sendingBlockingQueue.BlockingQueue#addAll(java.util.List)
     */
    @Override
    public void addAll(List<T> objects) {
        synchronized (queue) {
            queue.addAll(objects);
            // wake up all the waiting threads as there are more then 1 object to
            // process
            queue.notifyAll();
        }

    }

}

